/*
 * @描述: 登录数据请求
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { loginAccount, getSmsCaptcha, compareCaptcha } from '@/services/userApi';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(loginAccount, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response
      });
      // Login successfully
      if (response.status === 'ok') {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        yield put(routerRedux.replace(redirect || '/'));
      }
    },
    *getCaptcha({ payload }, { call }) {
      yield call(getSmsCaptcha, payload);
    },
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest'
        }
      });
      localStorage.removeItem('mscode_token');
      localStorage.removeItem('mscode_menu');
      localStorage.removeItem('mscode_menubutton');
      localStorage.setItem('mscode_authority', 'guest');
      reloadAuthorized();
      const { redirect } = getPageQuery();
      // redirect
      if (window.location.pathname !== '/user/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href
            })
          })
        );
      }
    },
    *compareCaptcha({ payload }, { call, put }) {
      const response = yield call(compareCaptcha, payload);
      yield put({
        type: 'save',
        payload: response
      });
      if (!response.message) return;
      return response;
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload ? payload.currentAuthority : 'guest');
      return {
        ...state,
        status: payload ? payload.status : false,
        type: payload ? payload.type : ''
      };
    },
    save(state, action) {
      return {
        ...state,
        data: action.payload.data
      };
    },
  }
};
